﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Util
{
    public static class AutoManagerUtil
    {

        /// <summary>
        ///  类型映射,默认字段名字一一对应 
        /// .ForMember(d => d.DestName, opt => opt.MapFrom(s => s.Name))  //指定字段一一对应    
        /// .ForMember(d => d.Birthday, opt => opt.MapFrom(src => src.Birthday.ToString("yy-MM-dd HH:mm")))//指定字段，并转化指定的格式    
        /// .ForMember(d => d.Age, opt => opt.Condition(src => src.Age > 5))//条件赋值    
        /// .ForMember(d => d.A1, opt => opt.Ignore())//忽略该字段，不给该字段赋值   
        /// .ForMember(d => d.A1, opt => opt.NullSubstitute("Default Value"))//如果源字段值为空，则赋值为 Default Value    
        /// .ForMember(d => d.A1, opt => opt.MapFrom(src => src.Name + src.Age * 3 + src.Birthday.ToString("d"))));//可以自己随意组合赋值
        /// </summary>
        /// <typeparam name="R">返回实体</typeparam>
        /// <typeparam name="S">目标实体</typeparam>
        /// <param name="S"></param>
        /// <returns>转换之后的实体</returns>
        public static R AutoFormModel<R, S>(this S s, Action<IMappingExpression<S, R>> action) where R : class where S : class
        {
            R r = default(R);
            if (s == null)
                return r;

            var config = new MapperConfiguration(cfg =>
            {
                var param = cfg.CreateMap<S, R>();
                action.Invoke(param);
            });
            var map = config.CreateMapper();
            return map.Map<R>(s);
        }

        /// <summary> 
        /// 集合列表类型映射,默认字段名字一一对应 
        /// </summary>
        /// <typeparam name="TDestination">转化之后的model，可以理解为viewmodel</typeparam> 
        /// <typeparam name="TSource">要被转化的实体，Entity</typeparam> 
        /// <param name="source">可以使用这个扩展方法的类型，任何引用类型</param> 
        /// <returns>转化之后的实体列表</returns> 
        public static IEnumerable<R> MapToList<R, S>(this IEnumerable<S> source, Action<IMappingExpression<S, R>> action)
           where R : class where S : class
        {
            if (source == null)
                return new List<R>();

            var config = new MapperConfiguration(cfg =>
            {
                var param = cfg.CreateMap<S, R>();
                action.Invoke(param);
            });

            var mapper = config.CreateMapper();
            return mapper.Map<List<R>>(source);
        }
    }
}
